//
//  BonjourNotifier.m
//  Cidney
//
//  Created by Chris Karr on 1/13/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BonjourNotifier.h"
#import "BonjourListener.h"
#import "Dispatcher.h"
#import <AddressBook/AddressBook.h>

@implementation BonjourNotifier

@synthesize lastCall;

- (NSString *) machineName
{
	CFStringRef nameRef;
	NSString * computerName;
	nameRef = CSCopyMachineName ();
	computerName = [NSString stringWithString:(NSString *) nameRef];
	CFRelease (nameRef);

	return computerName;
}

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incoming:) name:INCOMING_CALL object:nil];
}

- (void) incoming:(NSNotification *) theNote
{
	self.lastCall = [theNote userInfo];

	NSNetServiceBrowser * bonjour = [[NSNetServiceBrowser alloc] init];
	[bonjour setDelegate:self];
	
	[bonjour searchForServicesOfType:@"_cidney._tcp." inDomain:@"local"];
	
	[[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(stopBonjour:) userInfo:
		[NSDictionary dictionaryWithObject:bonjour forKey:@"bonjour"] repeats:NO] retain];
}

- (void) stopBonjour:(NSTimer *) theTimer
{
	// [[[theTimer userInfo] valueForKey:@"bonjour"] release];
	[theTimer release];
}

- (void) netServiceBrowser:(NSNetServiceBrowser *) netServiceBrowser didFindService:(NSNetService *) netService 
	moreComing:(BOOL) moreServicesComing
{
	[netService retain];
	[netService setDelegate:self];
	[netService resolveWithTimeout:1.0];
	
	[netServiceBrowser release];
}

- (void) netServiceDidResolveAddress:(NSNetService *) netService
{
	if ([[self machineName] isEqual:[netService name]])
	{
	
	}
	else if ([self.lastCall valueForKey:BONJOUR_KEY] != nil)
	{

	}
	else // if ([self.lastCall valueForKey:[netService name]] == nil)
	{
		NSSocketPort * port = [[NSSocketPort alloc] initRemoteWithTCPPort:[netService port] host:[netService hostName]];
		NSConnection * connection = [NSConnection connectionWithReceivePort:nil sendPort:port];
	
		remoteObject = (id<CidneyProtocol>) [connection rootProxy];
	
		NSData * image = nil;
	
		ABPerson * person = [self.lastCall valueForKey:PERSON_KEY];
	
		if (person != nil)
			image = [person imageData];
	
		[remoteObject incomingCaller:[self.lastCall valueForKey:NAME_KEY] number:[self.lastCall valueForKey:NUMBER_KEY]	image:image];
		
		// [self.lastCall setValue:[NSNumber numberWithBool:YES] forKey:[netService name]];
	
		[port release];
		[connection release];
	}
	
	[netService release];
}

@end
